package com.geekyang.rabbitmqapi.confirmlistener;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author ccyang
 * @date 2018/10/14 10:58
 * 消息确认机制：生产者
 */
public class Producer {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1 创建 ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("39.106.128.50");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2 创建 Connection
        Connection connection = connectionFactory.newConnection();

        //3 通过 Connection 创建 Channel
        Channel channel = connection.createChannel();

        //4 指定消息投递模式：消息的确认模式
        channel.confirmSelect();

        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.save";

        //5 发送消息
        String msg = "Hello RabbitMQ Send confirm message.";
        channel.basicPublish(exchangeName,routingKey,null,msg.getBytes());

        //6 添加一个确认监听
        channel.addConfirmListener(new ConfirmListener() {
            // ack 时执行该方法
            @Override
            public void handleAck(long l, boolean b) throws IOException {
                System.err.println("---------------Ack!---------------");
            }
            // 失败时执行该方法
            @Override
            public void handleNack(long l, boolean b) throws IOException {
                System.err.println("---------------no ack!--------------");
            }
        });

    }

}
